﻿using CSRedis;
using SH.Common;
using SH.Common.CommonReturn;
using SH.Multitenant.Application.IServices.IRole;
using SH.Multitenant.Domain.RBAC;
using SH.Multitenant.Infrastructure.IRepository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace SH.Multitenant.Application.Services
{
    public class RoleServices : BaseServices<Role>, IRoleServices
    {
        private readonly IRoleRepository _roleRepository;
        private readonly IRolePermissionRepository _rolePermissionRepository;
        private readonly CSRedisClient _redis = new CSRedisClient(AppService.Configuration["redisIP"]);

        public RoleServices(IRoleRepository repository, IRolePermissionRepository rolePermissionRepository) : base(repository)
        {
            _roleRepository = repository;
            _rolePermissionRepository = rolePermissionRepository;
        }
        //条件分页获取角色列表
        public ApiPaging<List<Role>> PageQuery(string? roleName, int pageSize, int pageIndex)
        {
            var query = _roleRepository.All;
            Expression<Func<Role, bool>> predicate = x => true;
            if (!string.IsNullOrEmpty(roleName))
            {
                predicate = x => x.RoleName!.Contains(roleName);
            }
            return _roleRepository.PageQuery(query, predicate, "CreateTime desc", pageSize, pageIndex);
        }
        //角色添加       
        public async Task<int> RoleAddAsync(RoleDTO dto)
        {
            using var tran = _roleRepository.MultitenantUseTran();
            try
            {
                string tenantId = _redis.Get<string>("tenantId");
                Role r = new Role
                {
                    RoleName = dto.RoleName,
                    CreateTime = DateTime.Now,
                    //登录存租户id到缓存 这里取值
                    TenantId = tenantId,
                };
                var result = _roleRepository.Insert(r);
                List<Role_Permission> rps = new List<Role_Permission>();
                foreach (var item in dto.PIds)
                {
                    rps.Add(new Role_Permission
                    {
                        RoleId = result,
                        PId = item,
                        TenantId = tenantId,
                    });
                }
                result = await _rolePermissionRepository.BatchInsertAsync(rps);
                //更新Redis
                //var roleList = _roleRepository.GetListAsync();
                //_redis.HSet("roleList", tenantId, roleList);
                tran.CommitTran();
                return result;
            }
            catch (Exception)
            {
                tran.RollbackTran();
                throw;
            }

        }
        //批量删除
        public int BatchDelRoles(List<Role> roles)
        {
            using var tran = _roleRepository.MultitenantUseTran();
            try
            {
                //string tenantId = _redis.Get<string>("tenantId");
                List<Role_Permission> rps = new List<Role_Permission>();
                //删除角色权限关系
                foreach (var item in roles)
                {
                    var rp = _rolePermissionRepository.GetListByCondition(x => x.RoleId == item.RoleId && x.TenantId == item.TenantId);
                    rps.AddRange(rp);
                }
                var result = _roleRepository.BatchDelete(roles);
                result = _rolePermissionRepository.BatchDelete(rps);
                tran.CommitTran();
                return result;
            }
            catch (Exception)
            {
                tran.RollbackTran();
                throw;
            }
        }
    }
}
